<template>
  <el-dialog
			title="编辑个人信息"
			:visible.sync="dialogVisible"
			width="500px"
      @close="show"
			:modal="false">
			<el-form ref="formregister" :rules="registerrules" :model="register" label-width="80px">
          <el-form-item label="头像" class="imgform" prop="user_pic">
            <div v-if="register.user_pic != ''" @click="$refs.imgfile.click()">
               <el-image
                  style="width:60px;height:60px;cursor: pointer;"
                  :src="register.user_pic"
                  :fit="'fit'">
                </el-image>
            </div>
            <div v-else @click="$refs.imgfile.click()" class="addimg">
              +
            </div>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input :disabled="true" placeholder="请输入邮箱" v-model="register.email"></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input placeholder="请输入昵称" v-model="register.nickname"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="username">
              <el-input placeholder="请输入姓名" type="text" v-model="register.username"></el-input>
          </el-form-item>
        </el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="show">取 消</el-button>
				<el-button :disabled="disabled" type="primary" @click="clickregister">确 定</el-button>
			</span>
      <input type="file" ref="imgfile" v-show="false"  @change="addimg()"/>
		</el-dialog>
</template>
<script>
import * as imageConversion from 'image-conversion'
export default {
  props:{
    dialogVisible:{
      type:Boolean,
      default:false
    }
  },
  created(){
    this.query()
  },
  data() {
    return {
      disabled:false,
      register:{
        nickname:'',
        username:'',
        user_pic:''
      },
      registerrules:{
          nickname: [
            { required: true, message: '请输入昵称', trigger: 'blur' },
            { min: 1, max: 12, message: '昵称最长位12个字符', trigger: 'blur' }
          ],
          username: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          user_pic: [
            {required: true, message: '请添加头像', trigger: 'change' }
          ],
      },
    }
  },
  methods:{
    show(){
      this.$emit('closedialog')
    },
    query(){
      if(this.$userInfo.token == '') return 
      this.$http.get('/my/userinfo').then(res => {
        if(res.status == 0){
					this.register = res.message[0]
        }else{
          this.$message({
            message: res.message,
            type: 'error'
          });
        }
      }).catch(err => {
        this.$message({
            message: err,
            type: 'error'
          });
      })
    },
    clickregister(){
      this.$refs['formregister'].validate((valid) => {
          if (valid) {
            this.disabled = true
            this.register.uid = this.$userInfo._id
            this.$http.post('/artcate/updateuserinfo',this.register).then(res => {
              if(res.status == 0){
                this.$message({
                  message: '修改成功！',
                  type: 'success'
                });
                this.$user_pic = this.register.user_pic
                localStorage.setItem("user_pic",this.$user_pic)
                this.$userInfo.username = this.register.username
                this.$userInfo.nickname = this.register.nickname
                localStorage.setItem("userInfo",escape(JSON.stringify(this.$userInfo)))
              }else{
                this.$message({
                  message: res.message,
                  type: 'error'
                });
              }
              this.disabled = false
            }).catch(err => {
              this.disabled = false
              this.$message({
                  message: err,
                  type: 'error'
                });
            })
          }
      })
    },
    async addimg(){
      if(this.$refs.imgfile.files.length == 0) return
      let name = ['jpg','png','jpge']
      let na = this.$refs.imgfile.files[0].name.split('.')
      let i = name.findIndex(item => item.toLocaleUpperCase() == na[1].toLocaleUpperCase())
      if(i == -1){
        this.$message.warning('仅支持png、jpg、jpge格式图片')
        return
      }
      if(this.$refs.imgfile.files[0].size/1024/1024 > 3){
        this.$message.warning('头像最大支持3MB')
        return
      }
      let files = this.$refs.imgfile.files[0];
      let file = await this.compressImg(files)
      var reader = new FileReader();
      reader.readAsDataURL(file); //调用自带方法进行转换
      reader.onload = (e) => {
        this.register.user_pic = e.target.result
        this.$refs.formregister.validateField('user_pic')
      }
    },
    compressImg(file){
      return new Promise((resolve, reject) => {
          imageConversion.compressAccurately(file, 30).then(res => {
            res = new File([res], file.name, { type: res.type, lastModified: Date.now() })
            resolve(res)
          })
      })
    },
  }
}
</script>
<style scoped>
div /deep/.imgform .el-form-item__content {
    position: relative;
    font-size: 14px;
    line-height: 0;
}
.addimg{
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #aca8a8;
  color: #aca8a8;
  cursor: pointer;
}
</style>